package com.tinckay.common.util;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author yuanjie
 */
public class HttpContextUtils {

    /**
     * 获取HttpServletRequest对象
     *
     * @return
     */
    public static HttpServletRequest getHttpServletRequest() {
        return getServletRequestAttributes().getRequest();
    }

    /**
     * 获取ServletRequestAttributes对象
     *
     * @return
     */
    public static ServletRequestAttributes getServletRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    /**
     * Description: 获取请求url
     *
     * @return
     */
    public static String getDomain() {
        HttpServletRequest request = getHttpServletRequest();
        StringBuffer url = request.getRequestURL();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
    }

    /**
     * Description: 获取HttpServletRequest最初请求
     *
     * @return
     */
    public static String getOrigin() {
        return getHttpServletRequest().getHeader("Origin");
    }

    /**
     * 获取session
     */
    public static HttpSession getSession() {
        return getHttpServletRequest().getSession();
    }

    /**
     * 获取attribute
     */
    public static Object getAttribute(String name) {
        return getSession().getAttribute(name);
    }

    /**
     * 设置attribute
     */
    public static void setAttribute(String name, Object value) {
        getSession().setAttribute(name, value);
    }


}
